// 全局变量定义
const xhrList = document.getElementById('xhrList');
const clearBtn = document.getElementById('clearBtn');
const configInfo = document.getElementById('configInfo');
const requests = []; // 存储所有XHR请求的数组
const keyMap = new Map(); // 存储解密密钥的映射表

// 默认配置
const defaultConfig = {
    decryptMethod: 'timestamp-traceid', // 解密方案选择
    enableAutoDecrypt: false
};

// 当前配置
let currentConfig = { ...defaultConfig };

// 初始化事件监听器
clearBtn.addEventListener('click', function () {
    requests.length = 0;
    keyMap.clear();
    render();
});

// 加载用户配置
function loadUserConfig() {
    chrome.storage.sync.get(['encryptionConfig'], function (result) {
        if (result.encryptionConfig) {
            currentConfig = { ...defaultConfig, ...result.encryptionConfig };
        }
        console.log('当前解密配置:', currentConfig);
        updateConfigInfo();
    });
}

// 更新配置信息显示
function updateConfigInfo() {
    const decryptMethodNames = {
        'timestamp-traceid': '雪花算法',
        'uuid-based': '冒泡算法',
        'custom-logic': '线性算法'
    };

    const decryptMethodName = decryptMethodNames[currentConfig.decryptMethod] || currentConfig.decryptMethod;
    const autoDecryptStatus = currentConfig.enableAutoDecrypt ? '自动解密' : '手动解密';

    configInfo.textContent = `${decryptMethodName} | ${autoDecryptStatus}`;
}

/**
 * 获取相对URL路径
 * @param {string} fullUrl - 完整的URL地址
 * @returns {string} 返回相对路径（不包含域名）
 */
function getRelativeUrl(fullUrl) {
    try {
        const url = new URL(fullUrl);
        return url.pathname + url.search;
    } catch (e) {
        console.error('URL解析失败:', fullUrl, e);
        return fullUrl;
    }
}

/**
 * 解密响应数据（已废弃，保留兼容性）
 * @param {string} encryptedData - 加密的数据
 * @param {string} url - 请求URL
 * @param {object} headers - 请求头
 * @param {object} requestData - 请求数据
 * @returns {null} 始终返回null
 */
function decryptResponse(encryptedData, url, headers = {}, requestData = {}) {
    return null;
}

/**
 * 生成解密密钥
 * @param {object} headers - 请求头对象
 * @returns {string|null} 返回解密密钥或null
 */
function generateDecryptionKey(headers) {
    const config = currentConfig;

    switch (config.keyGeneration) {
        case 'timestamp-traceid':
            return generateTimestampTraceIdKey(headers);
        case 'uuid-only':
            return generateUuidOnlyKey(headers);
        case 'custom':
            return generateCustomKey();
        case 'header-based':
            return generateHeaderBasedKey(headers);
        default:
            return generateTimestampTraceIdKey(headers);
    }
}

/**
 * 生成时间戳+追踪ID密钥
 * @param {object} headers - 请求头对象
 * @returns {string|null} 返回16位密钥或null
 */
function generateTimestampTraceIdKey(headers) {
    const timestamp = headers['time'] || headers['timestamp'];
    const traceId = headers['traceid'] || headers['TraceId'] || headers['trace-id'];

    if (timestamp && traceId) {
        const timestampNum = Number(timestamp);
        const traceIdStr = String(traceId);
        return (timestampNum + traceIdStr).slice(0, 16);
    }
    return null;
}

/**
 * 生成仅UUID密钥
 * @param {object} headers - 请求头对象
 * @returns {string|null} 返回16位密钥或null
 */
function generateUuidOnlyKey(headers) {
    const uuid = headers['uuid'] || headers['UUID'];
    if (uuid) {
        return String(uuid).slice(0, 16);
    }
    return null;
}

/**
 * 生成自定义密钥
 * @returns {string|null} 返回自定义密钥或null
 */
function generateCustomKey() {
    const customKey = currentConfig.customKey;
    if (customKey && customKey.length >= 16) {
        return customKey.slice(0, 16);
    }
    return null;
}

/**
 * 生成基于请求头的密钥
 * @param {object} headers - 请求头对象
 * @returns {string|null} 返回16位密钥或null
 */
function generateHeaderBasedKey(headers) {
    const field1 = currentConfig.headerField1;
    const field2 = currentConfig.headerField2;
    const separator = currentConfig.headerSeparator;

    const value1 = headers[field1.toLowerCase()] || headers[field1];
    const value2 = headers[field2.toLowerCase()] || headers[field2];

    if (value1 && value2) {
        const combined = value1 + separator + value2;
        return combined.slice(0, 16);
    } else if (value1) {
        return String(value1).slice(0, 16);
    }
    return null;
}

/**
 * AES解密函数（旧版本，保留兼容性）
 * @param {string} encryptedData - 加密的数据
 * @param {string} key - 解密密钥
 * @returns {string|null} 解密后的数据或null
 */
function decryptAES(encryptedData, key) {
    const paddedKey = key.padEnd(16, '0').slice(0, 16);

    try {
        const decrypt = CryptoJS.AES.decrypt(encryptedData, CryptoJS.enc.Utf8.parse(paddedKey), {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7,
        });

        const result = decrypt.toString(CryptoJS.enc.Utf8);

        if (!result) {
            return null;
        }

        return result;
    } catch (e) {
        return null;
    }
}

/**
 * 主要的解密函数
 * @param {string} encryptedData - 需要解密的数据
 * @param {string} keyStr - 解密密钥
 * @returns {string|null} 解密后的字符串或null
 */
function Decrypt(encryptedData, keyStr) {
    if (!encryptedData || !keyStr) return null;

    try {
        // 清理输入数据：移除空格和双引号
        const cleanData = encryptedData.replace(/\s/g, '').replace(/"/g, '');
        const cleanKey = keyStr.replace(/\s/g, '').replace(/"/g, '');

        // 使用AES-ECB解密（默认算法）
        return decryptAESECB(cleanData, cleanKey);
    } catch (error) {
        console.error('解密失败:', error);
        return null;
    }
}

/**
 * AES-ECB解密
 * @param {string} encryptedData - 加密数据
 * @param {string} key - 密钥
 * @returns {string|null} 解密结果
 */
function decryptAESECB(encryptedData, key) {
    const paddedKey = key.padEnd(16, '0').slice(0, 16);

    try {
        const decrypt = CryptoJS.AES.decrypt(encryptedData, CryptoJS.enc.Utf8.parse(paddedKey), {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7,
        });

        const result = decrypt.toString(CryptoJS.enc.Utf8);
        return result || null;
    } catch (error) {
        console.error('AES-ECB解密失败:', error);
        return null;
    }
}



/**
 * 格式化JSON数据
 * @param {string} data - 需要格式化的数据
 * @returns {string|null} 格式化后的JSON字符串或null
 */
function formatJSON(data) {
    if (!data || data === '无请求数据' || data === '无响应数据') {
        return null;
    }

    try {
        // 尝试解析JSON并重新格式化
        const parsed = JSON.parse(data);
        return JSON.stringify(parsed, null, 2);
    } catch (e) {
        // 如果不是有效的JSON，直接返回原数据
        return data;
    }
}

/**
 * HTML转义函数
 * @param {string} text - 需要转义的文本
 * @returns {string} 转义后的HTML字符串
 */
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

/**
 * 复制文本到剪贴板
 * @param {HTMLElement} button - 复制按钮元素
 * @param {string} text - 要复制的文本内容
 */
function copyToClipboard(button, text) {
    // 创建一个临时的textarea元素
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed';
    textarea.style.left = '-9999px';
    textarea.style.top = '-9999px';
    document.body.appendChild(textarea);

    try {
        textarea.select();
        textarea.setSelectionRange(0, 99999); // 兼容移动设备

        const successful = document.execCommand('copy');

        if (successful) {
            // 显示成功提示
            showCopyNotification('✅ 复制成功！', 'success');

            // 更新按钮状态
            const originalText = button.textContent;
            button.textContent = '已复制!';
            button.classList.add('copied');

            setTimeout(function () {
                button.textContent = originalText;
                button.classList.remove('copied');
            }, 2000);
        } else {
            showCopyNotification('❌ 复制失败，请手动复制', 'error');
        }
    } catch (err) {
        showCopyNotification('❌ 复制失败，请手动复制', 'error');
    } finally {
        document.body.removeChild(textarea);
    }
}

/**
 * 显示复制操作的通知消息
 * @param {string} message - 通知消息内容
 * @param {string} type - 通知类型（'success' 或 'error'）
 */
function showCopyNotification(message, type) {
    // 移除已存在的通知
    const existingNotification = document.querySelector('.copy-notification');
    if (existingNotification) {
        existingNotification.remove();
    }

    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `copy-notification ${type}`;
    notification.textContent = message;

    document.body.appendChild(notification);

    // 3秒后自动移除
    setTimeout(function () {
        notification.style.animation = 'slideOut 0.3s ease';
        setTimeout(function () {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

/**
 * 绑定复制按钮的点击事件
 */
function bindCopyButtons() {
    const copyButtons = document.querySelectorAll('.copy-btn');

    copyButtons.forEach(button => {
        button.addEventListener('click', function () {
            const index = parseInt(this.getAttribute('data-index'));
            const type = this.getAttribute('data-type');

            if (index >= 0 && index < requests.length) {
                const request = requests[index];
                let content = '';

                switch (type) {
                    case 'request':
                        content = formatJSON(request.requestData) || '无请求数据';
                        break;
                    case 'response':
                        content = formatJSON(request.responseData) || '无响应数据';
                        break;
                    case 'decrypted':
                        content = formatJSON(request.decryptedData) || '无解密数据';
                        break;
                    case 'decryptedRequest':
                        content = formatJSON(request.decryptedRequestData) || '无解密请求数据';
                        break;
                    case 'requestHeaders':
                        content = JSON.stringify(request.requestHeaders, null, 2) || '无请求头数据';
                        break;
                    case 'responseHeaders':
                        content = JSON.stringify(request.responseHeaders, null, 2) || '无响应头数据';
                        break;
                }

                copyToClipboard(this, content);
            }
        });
    });
}

/**
 * 绑定展开/收缩事件的点击监听
 */
function bindToggleEvents() {
    const clickableHeaders = document.querySelectorAll('.xhr-header.clickable');

    clickableHeaders.forEach(header => {
        header.addEventListener('click', function () {
            const index = parseInt(this.getAttribute('data-index'));
            toggleDetails(index);
        });
    });
}

/**
 * 绑定解密按钮的点击事件
 */
function bindDecryptButtons() {
    const decryptButtons = document.querySelectorAll('.decrypt-btn');

    decryptButtons.forEach(button => {
        button.addEventListener('click', function () {
            const index = parseInt(this.getAttribute('data-index'));
            decryptRequestData(index);
        });
    });
}

/**
 * 切换请求详情的展开/收缩状态
 * @param {number} index - 请求在数组中的索引
 */
function toggleDetails(index) {
    const detailsContainer = document.getElementById(`details-${index}`);
    if (!detailsContainer) {
        return;
    }

    const header = detailsContainer.previousElementSibling;
    const expandIcon = header.querySelector('.expand-icon');

    if (detailsContainer.style.display === 'none' || detailsContainer.style.display === '') {
        detailsContainer.style.display = 'block';
        expandIcon.textContent = '▼';
        expandIcon.style.transform = 'rotate(0deg)';
    } else {
        detailsContainer.style.display = 'none';
        expandIcon.textContent = '▶';
        expandIcon.style.transform = 'rotate(0deg)';
    }
}

/**
 * 解密指定索引的请求数据
 * @param {number} index - 请求在数组中的索引
 */
function decryptRequestData(index) {
    if (index < 0 || index >= requests.length) {
        return;
    }

    const request = requests[index];
    const relativeUrl = getRelativeUrl(request.url);
    const startTime = Date.now();

    // 根据选择的解密方案进行解密
    const decryptMethod = currentConfig.decryptMethod;
    console.log('使用解密方案:', decryptMethod);

    let decryptedRequestData = null;
    let decryptedResponseData = null;
    let success = false;
    let error = null;

    try {
        switch (decryptMethod) {
            case 'timestamp-traceid':
                // 雪花算法：时间戳+追踪ID解密方案（原有逻辑）
                const result1 = decryptMethod1(request, relativeUrl);
                decryptedRequestData = result1.requestData;
                decryptedResponseData = result1.responseData;
                success = !!(decryptedRequestData || decryptedResponseData);
                break;
            case 'uuid-based':
                // 方案二：UUID基础解密方案
                const result2 = decryptMethod2(request, relativeUrl);
                decryptedRequestData = result2.requestData;
                decryptedResponseData = result2.responseData;
                success = !!(decryptedRequestData || decryptedResponseData);
                break;
            case 'custom-logic':
                // 线性算法：自定义逻辑解密方案
                const result3 = decryptMethod3(request, relativeUrl);
                decryptedRequestData = result3.requestData;
                decryptedResponseData = result3.responseData;
                success = !!(decryptedRequestData || decryptedResponseData);
                break;
            default:
                error = '未知的解密方案';
                showCopyNotification('❌ 未知的解密方案', 'error');
                return;
        }
    } catch (err) {
        error = err.message;
        success = false;
    }

    const duration = Date.now() - startTime;
    const domain = new URL(request.url).hostname;

    // 记录统计信息
    recordDecryptionStats(decryptMethod, success, duration, domain, error);

    // 更新解密结果
    if (decryptedRequestData) {
        request.decryptedRequestData = decryptedRequestData;
    }
    if (decryptedResponseData) {
        request.decryptedData = decryptedResponseData;
    }

    // 更新按钮状态（仅在手动解密模式下）
    if (!currentConfig.enableAutoDecrypt) {
        const decryptBtn = document.querySelector(`.decrypt-btn[data-index="${index}"]`);
        if (decryptBtn) {
            decryptBtn.textContent = '✅ 已解密';
            decryptBtn.disabled = true;
            decryptBtn.style.background = '#4ec9b0';
        }
    }

    // 重新渲染
    render();

    // 确保面板保持展开状态
    const detailsContainer = document.getElementById(`details-${index}`);
    if (detailsContainer) {
        detailsContainer.style.display = 'block';
        const header = detailsContainer.previousElementSibling;
        const expandIcon = header.querySelector('.expand-icon');
        if (expandIcon) {
            expandIcon.textContent = '▼';
        }
    }

    // 仅在手动解密模式下显示通知
    if (!currentConfig.enableAutoDecrypt) {
        showCopyNotification('✅ 解密完成！', 'success');
    }
}

/**
 * 记录解密统计信息
 * @param {string} algorithm - 使用的算法
 * @param {boolean} success - 是否成功
 * @param {number} duration - 解密耗时
 * @param {string} domain - 域名
 * @param {string} error - 错误信息
 */
function recordDecryptionStats(algorithm, success, duration, domain, error) {
    // 发送消息到统计面板
    chrome.runtime.sendMessage({
        type: 'DECRYPTION_ATTEMPT',
        algorithm: algorithm,
        success: success,
        duration: duration,
        domain: domain,
        error: error
    }).catch(() => {
        // 如果统计面板未打开，忽略错误
    });

    // 同时保存到本地存储
    chrome.storage.local.get(['decryptionStats'], (result) => {
        const stats = result.decryptionStats || {
            totalRequests: 0,
            successfulDecryptions: 0,
            failedDecryptions: 0,
            algorithms: {
                'timestamp-traceid': { name: '雪花算法', count: 0, success: 0, totalTime: 0, lastUsed: null },
                'uuid-based': { name: '冒泡算法', count: 0, success: 0, totalTime: 0, lastUsed: null },
                'custom-logic': { name: '线性算法', count: 0, success: 0, totalTime: 0, lastUsed: null }
            },
            domains: {},
            errors: {},
            timeSeries: []
        };

        // 更新总体统计
        stats.totalRequests++;
        if (success) {
            stats.successfulDecryptions++;
        } else {
            stats.failedDecryptions++;
        }

        // 更新算法统计
        if (stats.algorithms[algorithm]) {
            stats.algorithms[algorithm].count++;
            stats.algorithms[algorithm].totalTime += duration;
            stats.algorithms[algorithm].lastUsed = Date.now();

            if (success) {
                stats.algorithms[algorithm].success++;
            }
        }

        // 更新域名统计
        if (!stats.domains[domain]) {
            stats.domains[domain] = {
                requests: 0,
                success: 0,
                algorithms: {}
            };
        }
        stats.domains[domain].requests++;
        if (success) {
            stats.domains[domain].success++;
        }

        if (!stats.domains[domain].algorithms[algorithm]) {
            stats.domains[domain].algorithms[algorithm] = 0;
        }
        stats.domains[domain].algorithms[algorithm]++;

        // 记录错误
        if (error) {
            const errorType = categorizeError(error);
            if (!stats.errors[errorType]) {
                stats.errors[errorType] = {
                    count: 0,
                    lastOccurrence: null
                };
            }
            stats.errors[errorType].count++;
            stats.errors[errorType].lastOccurrence = Date.now();
        }

        // 记录时间序列数据
        stats.timeSeries.push({
            timestamp: Date.now(),
            success,
            algorithm,
            duration
        });

        // 保持时间序列数据在24小时内
        const oneDayAgo = Date.now() - (24 * 60 * 60 * 1000);
        stats.timeSeries = stats.timeSeries.filter(item => item.timestamp > oneDayAgo);

        // 保存统计
        chrome.storage.local.set({ 'decryptionStats': stats });
    });
}

/**
 * 错误分类
 * @param {string} error - 错误信息
 * @returns {string} 错误类型
 */
function categorizeError(error) {
    if (error.includes('Invalid key')) return '密钥错误';
    if (error.includes('Invalid padding')) return '填充错误';
    if (error.includes('Malformed')) return '数据格式错误';
    if (error.includes('timeout')) return '超时错误';
    return '其他错误';
}

/**
 * 雪花算法：时间戳+追踪ID解密方案（原有逻辑）
 * @param {object} request - 请求对象
 * @param {string} relativeUrl - 相对URL
 * @returns {object} 解密结果
 */
function decryptMethod1(request, relativeUrl) {
    // 从keyMap中查找对应的密钥
    let foundKeyInfo = null;
    for (let [key, value] of keyMap.entries()) {
        if (key.startsWith(relativeUrl + '/')) {
            foundKeyInfo = value;
            break;
        }
    }

    if (!foundKeyInfo || !foundKeyInfo.decryptionKey) {
        console.log('雪花算法：未找到解密密钥');
        return { requestData: null, responseData: null };
    }

    const decryptionKey = foundKeyInfo.decryptionKey;
    console.log('雪花算法：使用密钥', decryptionKey);

    let decryptedRequestData = null;
    let decryptedResponseData = null;

    // 解密请求数据
    if (request.requestData && request.requestData !== '无请求数据' && request.requestData !== '无查询参数') {
        try {
            const cleanRequestData = request.requestData.trim();
            const parsedRequest = JSON.parse(cleanRequestData);

            if (parsedRequest.data) {
                const decrypted = Decrypt(parsedRequest.data, decryptionKey);
                if (decrypted) {
                    try {
                        const parsedData = JSON5.parse(decrypted);
                        decryptedRequestData = JSON.stringify(parsedData, null, 2);
                    } catch (e) {
                        decryptedRequestData = decrypted;
                    }
                }
            }
        } catch (e) {
            console.error('雪花算法：请求数据解密失败:', e);
        }
    }

    // 解密响应数据
    if (request.responseData && request.responseData !== '无响应数据') {
        try {
            const cleanResponseData = request.responseData.trim();
            const decrypted = Decrypt(cleanResponseData, decryptionKey);
            if (decrypted) {
                try {
                    const parsedData = JSON5.parse(decrypted);
                    decryptedResponseData = JSON.stringify(parsedData, null, 2);
                } catch (e) {
                    decryptedResponseData = decrypted;
                }
            }
        } catch (e) {
            console.error('雪花算法：响应数据解密失败:', e);
        }
    }

    return { requestData: decryptedRequestData, responseData: decryptedResponseData };
}

/**
 * 解密方案二：UUID基础解密方案
 * @param {object} request - 请求对象
 * @param {string} relativeUrl - 相对URL
 * @returns {object} 解密结果
 */
function decryptMethod2(request, relativeUrl) {
    // 从请求头中获取UUID
    const headers = request.requestHeaders;
    const uuid = headers['traceid'] || headers['Traceid'];

    if (!uuid) {
        console.log('方案二：未找到UUID');
        return { requestData: null, responseData: null };
    }

    // 使用UUID作为密钥（使用MD5哈希后取中间16位）
    const decryptionKey = CryptoJS.MD5(uuid).toString().substring(8, 24);
    console.log('冒泡算法：使用UUID密钥', uuid);

    let decryptedRequestData = null;
    let decryptedResponseData = null;

    // 解密请求数据
    if (request.requestData && request.requestData !== '无请求数据' && request.requestData !== '无查询参数') {
        try {
            const cleanRequestData = request.requestData.trim();
            const parsedRequest = JSON.parse(cleanRequestData);

            if (parsedRequest.data) {
                const decrypted = Decrypt(parsedRequest.data, decryptionKey);
                if (decrypted) {
                    try {
                        const parsedData = JSON5.parse(decrypted);
                        decryptedRequestData = JSON.stringify(parsedData, null, 2);
                    } catch (e) {
                        decryptedRequestData = decrypted;
                    }
                }
            }
        } catch (e) {
            console.error('方案二：请求数据解密失败:', e);
        }
    }

    // 解密响应数据
    if (request.responseData && request.responseData !== '无响应数据') {
        try {
            const cleanResponseData = request.responseData.trim();
            const decrypted = Decrypt(cleanResponseData, decryptionKey);
            if (decrypted) {
                try {
                    const parsedData = JSON5.parse(decrypted);
                    decryptedResponseData = JSON.stringify(parsedData, null, 2);
                } catch (e) {
                    decryptedResponseData = decrypted;
                }
            }
        } catch (e) {
            console.error('方案二：响应数据解密失败:', e);
        }
    }

    return { requestData: decryptedRequestData, responseData: decryptedResponseData };
}

/**
 * 线性算法：自定义逻辑解密方案
 * @param {object} request - 请求对象
 * @param {string} relativeUrl - 相对URL
 * @returns {object} 解密结果
 */
function decryptMethod3(request, relativeUrl) {
    // 从请求头中获取自定义字段
    const headers = request.requestHeaders;
    const customField1 = headers['customfield1'] || headers['custom-field-1'];
    const customField2 = headers['customfield2'] || headers['custom-field-2'];

    if (!customField1) {
        console.log('线性算法：未找到自定义字段');
        return { requestData: null, responseData: null };
    }

    // 使用自定义字段组合生成密钥
    let decryptionKey;
    if (customField2) {
        decryptionKey = (customField1 + '-' + customField2).slice(0, 16);
    } else {
        decryptionKey = String(customField1).slice(0, 16);
    }

    console.log('线性算法：使用自定义密钥', decryptionKey);

    let decryptedRequestData = null;
    let decryptedResponseData = null;

    // 解密请求数据
    if (request.requestData && request.requestData !== '无请求数据' && request.requestData !== '无查询参数') {
        try {
            const cleanRequestData = request.requestData.trim();
            const parsedRequest = JSON.parse(cleanRequestData);

            if (parsedRequest.data) {
                const decrypted = Decrypt(parsedRequest.data, decryptionKey);
                if (decrypted) {
                    try {
                        const parsedData = JSON5.parse(decrypted);
                        decryptedRequestData = JSON.stringify(parsedData, null, 2);
                    } catch (e) {
                        decryptedRequestData = decrypted;
                    }
                }
            }
        } catch (e) {
            console.error('线性算法：请求数据解密失败:', e);
        }
    }

    // 解密响应数据
    if (request.responseData && request.responseData !== '无响应数据') {
        try {
            const cleanResponseData = request.responseData.trim();
            const decrypted = Decrypt(cleanResponseData, decryptionKey);
            if (decrypted) {
                try {
                    const parsedData = JSON5.parse(decrypted);
                    decryptedResponseData = JSON.stringify(parsedData, null, 2);
                } catch (e) {
                    decryptedResponseData = decrypted;
                }
            }
        } catch (e) {
            console.error('线性算法：响应数据解密失败:', e);
        }
    }

    return { requestData: decryptedRequestData, responseData: decryptedResponseData };
}

/**
 * 解析请求数据（POST请求体或GET查询参数）
 * @param {object} request - 请求对象
 * @returns {string} 解析后的请求数据
 */
function parseRequestData(request) {
    let requestData = '无请求数据';

    if (request.request.postData) {
        const rawRequestData = request.request.postData.text;

        // 先尝试解析为JSON
        try {
            requestData = JSON.stringify(JSON.parse(rawRequestData), null, 2);
        } catch (e) {
            requestData = rawRequestData;
        }
    } else if (request.request.method === 'GET') {
        // 对于GET请求，解析URL查询参数
        try {
            const url = new URL(request.request.url);
            const searchParams = url.searchParams;
            const queryParams = {};

            // 将URLSearchParams转换为普通对象
            for (let [key, value] of searchParams.entries()) {
                queryParams[key] = value;
            }

            if (Object.keys(queryParams).length > 0) {
                requestData = JSON.stringify(queryParams, null, 2);
            } else {
                requestData = '无查询参数';
            }
        } catch (e) {
            requestData = 'URL解析失败';
        }
    }

    return requestData;
}

/**
 * 解析请求头信息
 * @param {object} request - 请求对象
 * @returns {object} 解析后的请求头对象
 */
function parseRequestHeaders(request) {
    const headers = {};
    if (request.request.headers) {
        request.request.headers.forEach(h => {
            headers[h.name.toLowerCase()] = h.value;
        });
    }
    return headers;
}

/**
 * 解析响应头信息
 * @param {object} request - 请求对象
 * @returns {object} 解析后的响应头对象
 */
function parseResponseHeaders(request) {
    const headers = {};
    if (request.response && request.response.headers) {
        request.response.headers.forEach(h => {
            headers[h.name.toLowerCase()] = h.value;
        });
    }
    return headers;
}

/**
 * 生成并存储解密密钥
 * @param {object} headers - 请求头对象
 * @param {string} url - 请求URL
 */
function generateAndStoreKey(headers, url) {
    const uuid = headers['uuid'] || headers['UUID'];

    // 使用新的密钥生成逻辑
    const decryptionKey = generateDecryptionKey(headers);

    if (decryptionKey && uuid) {
        const relativeUrl = getRelativeUrl(url);
        const keyMapKey = relativeUrl + '/' + uuid;
        keyMap.set(keyMapKey, {
            uuid: uuid,
            decryptionKey: decryptionKey,
            algorithm: currentConfig.algorithm,
            keyGeneration: currentConfig.keyGeneration
        });

        console.log('存储密钥:', {
            url: relativeUrl,
            uuid: uuid,
            key: decryptionKey,
            algorithm: currentConfig.algorithm,
            keyGeneration: currentConfig.keyGeneration
        });
    }
}

/**
 * 处理响应数据
 * @param {object} request - 请求对象
 * @param {function} callback - 处理完成后的回调函数
 */
function processResponseData(request, callback) {
    let responseData = '无响应数据';
    let decryptedData = null;

    if (request.response) {
        request.getContent(function (content, encoding) {
            if (content) {
                const cleanContent = content.trim();

                try {
                    const jsonData = JSON.parse(cleanContent);
                    responseData = JSON.stringify(jsonData, null, 2);
                } catch (e) {
                    responseData = cleanContent;
                }

                callback(responseData, decryptedData);
            }
        });
    } else {
        callback(responseData, decryptedData);
    }
}

/**
 * 渲染XHR请求列表到页面
 */
function render() {
    if (requests.length === 0) {
        xhrList.innerHTML = '<div style="text-align: center; padding: 40px; color: #6a9955;"><i>暂无XHR请求</i></div>';
        return;
    }

    xhrList.innerHTML = requests.map((item, index) => {
        const hasDecryptedData = item.decryptedData && item.decryptedData !== '无响应数据';
        const statusClass = hasDecryptedData ? 'status-success' : 'status-warning';

        return `<div class='xhr-item'>
            <div class='xhr-header clickable' data-index="${index}">
                <span class='status-indicator ${statusClass}'></span>
                <span class='method'>${item.method}</span>
                <span class='url'>${item.url}</span>
                <div class='time-info'>
                    <div class='time'>${item.time}</div>
                    <div class='duration'>${item.duration}ms</div>
                </div>
                <span class='expand-icon'>▶</span>
            </div>
            
            <div class='details-container' id='details-${index}' style='display: none;'>
                ${!currentConfig.enableAutoDecrypt ? `
                <div class='decrypt-controls'>
                    <button class='decrypt-btn' data-index="${index}">🔓 解密数据</button>
                </div>
                ` : ''}
                
                <details>
                    <summary>📤 请求头</summary>
                    <div class='code-container'>
                        <button class='copy-btn' data-index="${index}" data-type="requestHeaders">复制</button>
                        <pre class='request-headers'><code class='language-json'>${JSON.stringify(item.requestHeaders, null, 2) || '无请求头数据'}</code></pre>
                    </div>
                </details>
                
                <details>
                    <summary>📥 响应头</summary>
                    <div class='code-container'>
                        <button class='copy-btn' data-index="${index}" data-type="responseHeaders">复制</button>
                        <pre class='response-headers'><code class='language-json'>${JSON.stringify(item.responseHeaders, null, 2) || '无响应头数据'}</code></pre>
                    </div>
                </details>
                
                <details>
                    <summary>📤 ${item.method === 'GET' ? '查询参数' : '请求数据'}</summary>
                    <div class='data-comparison'>
                        <div class='data-column'>
                            <div class='data-label'>原始数据</div>
                            <div class='code-container'>
                                <button class='copy-btn' data-index="${index}" data-type="request">复制</button>
                                <pre class='request-data'><code class='language-json'>${formatJSON(item.requestData) || (item.method === 'GET' ? '无查询参数' : '无请求数据')}</code></pre>
                            </div>
                        </div>
                        ${item.decryptedRequestData ? `
                        <div class='data-column'>
                            <div class='data-label'>解密后数据</div>
                            <div class='code-container'>
                                <button class='copy-btn' data-index="${index}" data-type="decryptedRequest">复制</button>
                                <pre class='decrypted-request-data'><code class='language-json'>${formatJSON(item.decryptedRequestData)}</code></pre>
                            </div>
                        </div>
                        ` : ''}
                    </div>
                </details>
                
                <details>
                    <summary>📥 响应数据</summary>
                    <div class='data-comparison'>
                        <div class='data-column'>
                            <div class='data-label'>原始数据</div>
                            <div class='code-container'>
                                <button class='copy-btn' data-index="${index}" data-type="response">复制</button>
                                <pre class='response-data'><code class='language-json'>${formatJSON(item.responseData) || '无响应数据'}</code></pre>
                            </div>
                        </div>
                        ${hasDecryptedData ? `
                        <div class='data-column'>
                            <div class='data-label'>解密后数据</div>
                            <div class='code-container'>
                                <button class='copy-btn' data-index="${index}" data-type="decrypted">复制</button>
                                <pre class='decrypted-data'><code class='language-json'>${formatJSON(item.decryptedData)}</code></pre>
                            </div>
                        </div>
                        ` : ''}
                    </div>
                </details>
            </div>
        </div>`;
    }).join('');

    // 应用代码高亮
    if (typeof Prism !== 'undefined') {
        Prism.highlightAll();
    }

    // 重新绑定各种事件
    bindCopyButtons();
    bindToggleEvents();
    bindDecryptButtons();
}

/**
 * 处理XHR请求完成事件
 * @param {object} request - 完成的请求对象
 */
function handleRequestFinished(request) {
    if (request.request.url && request.request.method) {
        const acceptHeader = request.request.headers && request.request.headers.find(h =>
            h.name.toLowerCase() === 'accept'
        );

        const isXhrRequest = acceptHeader && acceptHeader.value.includes('application/json');

        if (isXhrRequest) {
            // 解析请求数据
            const requestData = parseRequestData(request);
            const decryptedRequestData = null;

            // 解析请求头
            const headers = parseRequestHeaders(request);

            // 生成并存储解密密钥
            generateAndStoreKey(headers, request.request.url);

            // 解析响应头
            const responseHeaders = parseResponseHeaders(request);

            // 计算请求时间信息
            const requestTime = new Date(request.startedDateTime).toLocaleString();

            // 使用当前时间作为响应时间，因为请求刚完成
            const currentTime = new Date();
            const responseTime = currentTime.toLocaleString();

            // 计算耗时：当前时间 - 开始时间
            const duration = Math.round(currentTime.getTime() - new Date(request.startedDateTime).getTime());

            // 调试信息
            console.log('时间调试信息:', {
                startedDateTime: request.startedDateTime,
                currentTime: currentTime.getTime(),
                duration: duration,
                requestTime: requestTime,
                responseTime: responseTime
            });

            // 查看完整的request对象结构
            console.log('完整的request对象:', request);

            // 处理响应数据
            processResponseData(request, (responseData, decryptedData) => {
                const lastRequest = requests[requests.length - 1];
                if (lastRequest) {
                    lastRequest.responseData = responseData;
                    lastRequest.decryptedData = decryptedData;
                    lastRequest.responseHeaders = responseHeaders;

                    // 在响应完成后重新计算耗时
                    const currentTime = new Date();
                    const actualDuration = Math.round(currentTime.getTime() - new Date(request.startedDateTime).getTime());
                    lastRequest.duration = actualDuration;
                    console.log('响应完成后的耗时:', actualDuration);

                    // 如果启用了自动解密，立即解密数据
                    if (currentConfig.enableAutoDecrypt) {
                        const requestIndex = requests.length - 1;
                        decryptRequestData(requestIndex);
                    }

                    render();
                }
            });

            // 添加请求到列表
            requests.push({
                url: request.request.url,
                method: request.request.method,
                time: requestTime,
                requestTime: requestTime,
                responseTime: responseTime,
                duration: duration,
                requestData: requestData,
                requestHeaders: headers,
                responseHeaders: responseHeaders,
                decryptedRequestData: decryptedRequestData,
                responseData: '无响应数据',
                decryptedData: null
            });
            render();
        }
    }
}

// 监听XHR请求完成事件
chrome.devtools.network.onRequestFinished.addListener(handleRequestFinished);

// 监听配置变化
chrome.storage.onChanged.addListener(function (changes, namespace) {
    if (namespace === 'sync' && changes.encryptionConfig) {
        currentConfig = { ...defaultConfig, ...changes.encryptionConfig.newValue };
        console.log('配置已更新:', currentConfig);
        updateConfigInfo();
        // 重新渲染以更新UI（显示/隐藏解密按钮等）
        render();
    }
});

// 初始化
loadUserConfig();
render();
